import axios from 'axios';
import { ElLoading } from 'element-plus'
import { ElMessage } from 'element-plus'

// 创建axios实列

// const routers = useRouter()
let loading = null
const service = axios.create({

  timeout: 8000,
  baseURL: "http://localhost:8000",
  withCredentials: true,
  headers: {
    "Content-Type": "application/json;charset=utf-8",
    'X-Requested-With': 'XMLHttpRequest',
    'Access-Control-Allow-Origin': '*'
  }
})


// 请求拦截，对增加一个loading的过程，统一处理
service.interceptors.request.use(config =>{

  loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    spinner: 'el-icon-loading',
    background: 'rgba(0, 0, 0, 0.7)',
  })

  console.log('请求进来了');
  return config
}, error => {
  return Promise.reject(`请求错误: ${error}`)
})


// 响应拦截，对返回值进行处理
service.interceptors.response.use( res =>{

  // 异步关闭loading
  loading.close()

  const code = res.data.code//code是后端的状态码
	if (code !== 200) {
		//请求失败（包括token失效，302，404...根据和后端约定好的状态码做出不同的处理）
		return Promise.reject(res)
	} else {
		//请求成功
		console.log(res, '成功----')
		return Promise.resolve(res.data)
	}
},error => {
  loading.close()
  ElMessage({
    message: '服务器错误！',
    type: 'error',
    duration: 2000,
    center: true,
  })
  return Promise.reject(`响应错误: ${error}`)
})


// post 请求
export const post = config => {
  return service({
    ...config,
    method: 'post',
    // data: config.data
  })
}


// get请求
export const get = config => {
  return service({
    ...config,
    method: 'get'
  })
}



export default service

